package com.sun.temp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sun.temp.bean.FilePath;
//import com.sun.temp.bean.PrdBcdQaPlanresultEx;
import com.sun.temp.bean.Qakansa;
import com.sun.temp.common.result.Result;
import com.sun.temp.mapper.mapper2.PrdBcdQaPlanresultDao;
import com.sun.temp.mapper.mapper3.QakansaDao;
//import com.sun.temp.netty.NettyClient;
//import com.sun.temp.netty.NettyManager;
import com.sun.temp.service.FilePathService;
import com.sun.temp.service.MaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;

import static java.lang.Thread.sleep;
import com.sun.temp.utils.LocalCache;


@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {

    @Resource
//    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

//    @Resource
//    private NettyClient nettyClient;

//    @Resource
//    private NettyManager nettyManager;

    @Autowired
    private FilePathService filePathService;

    @Autowired
    private MaterialService materialService;

    @Resource
    private QakansaDao qakansaDao;

    @Resource
    private PrdBcdQaPlanresultDao resultDao;

    /**
     * 测试 -- 创建本地文件夹，rpa第一步输入等级和文件夹目录
     * @return
     * @throws Exception
     */
    @GetMapping("/createFloderAndRpa1")
    public Result createFloderAndRpa1 () throws Exception{

        String grade = "G770HD-A6";
        String batchNo = "3077126";

//        this.createStorgeFolder(grade,batchNo);

//        sleep(2000);

        this.inputBacthAndGrade(batchNo,grade);

        return Result.success(true);
    }

    /**
     * 创建存储加热数据保存目录
     */
    public void createStorgeFolder(String grade, String batchNo){
        LocalDate currentDate = LocalDate.now();
        String path = "D:\\TMADATA\\G\\";
//        grade = "G770HD-A3";
//        batchNo = "4077123";
        // String foldPath = path + grade +"\\" +currentDate.getYear() + "\\" + batchNo;
        // 最后batchNo是文件名，不是文件夹
        String foldPath = path + grade +"\\" +currentDate.getYear();

        File newFolder = new File(foldPath);
        if(!newFolder.exists()){
            newFolder.mkdirs();

            // 文件目录存储到数据库表file_path
            FilePath filePath = filePathService.getOne(new QueryWrapper<FilePath>().eq("type", "1"));
            filePath.setFilepath(foldPath);
            filePathService.updateById(filePath);
        }
    }


    /**
     * RPA输入批次和等级
     * @return
     * @throws Exception
     */
    public Result inputBacthAndGrade( String batchNo,  String grade) throws Exception{

        // Python脚本路径及参数
        String pythonScript = "D:\\zydm\\code\\sumimoto-rob\\doc\\inputBacthAndGrade.py";

        // 要传递给Python脚本的参数
        String arg1 = grade;
        LocalDate currentDate = LocalDate.now();
        String path = "D:\\TMADATA\\G\\";
//        grade = "G770HD-A3";
//        batchNo = "4077123";
        String foldPath = path + grade +"\\" +currentDate.getYear() + "\\" + batchNo;
        String arg2 = foldPath;

        ProcessBuilder processBuilder = new ProcessBuilder("python", pythonScript, arg1, arg2);
        Process process = processBuilder.start();

        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        StringBuilder output = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            System.out.printf(line);
            output.append(line).append("\n");
        }

        int exitCode = -1;
        try {
            exitCode = process.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (exitCode == 0) {
                System.out.println("Python脚本成功运行！输出结果为:\n" + output.toString());
            } else {
                System.err.println("Python脚本运行失败！退出码为:" + exitCode);
            }

            process.destroy();
        }
        return Result.success();
    }


    /**
     * 视觉测试
     * @return
     */
    @GetMapping("/tcpTestSendT1")
    public Result tcpTestSendT1(){
//        nettyManager.init();
//        nettyClient.sendMessage("T1\r");
        return Result.success(true);
    }

    /**
     * oracleTestInset
     * @return
     */
    @GetMapping("/oracleTestInset")
    public Result oracleTestInset(){

        return Result.success(true);
    }



    /**
     * 脚本测试
     * @return
     * @throws Exception
     */
    @GetMapping("/pythonTest")
    public Result pythonTest() throws Exception{
//        needlePress();
        needleMove();
        return Result.success(true);
    }

    /**
     * 测试--顶针压紧--点击mesure弹出窗口、输入长度、点击startlenth........
     * @return
     * @throws Exception
     */
    public Result needlePress() throws Exception{

        // Python脚本路径及参数
        String pythonScript = "D:\\zydm\\code\\sumimoto-rob\\doc\\needlePress.py";
        pythnExcute(pythonScript);
        return Result.success();
    }

    /**
     * 测试--顶针上升move
     * @return
     * @throws Exception
     */
    public Result needleMove() throws Exception{

        // Python脚本路径及参数
        String pythonScript = "D:\\zydm\\code\\sumimoto-rob\\doc\\needleMove.py";
        pythnExcute(pythonScript);
        return Result.success();
    }

    /**
     * 测试--start开始加热
     * @return
     * @throws Exception
     */
    public Result startHeating() throws Exception {

        // Python脚本路径及参数
        String pythonScript = "D:\\zydm\\code\\sumimoto-rob\\doc\\startHeating.py";
        pythnExcute(pythonScript);
        return Result.success();
    }

    public void pythnExcute(String path) throws Exception{
        ProcessBuilder processBuilder = new ProcessBuilder("python", path);
        Process process = processBuilder.start();

        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        StringBuilder output = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            System.out.printf(line);
            output.append(line).append("\n");
        }

        int exitCode = -1;
        try {
            exitCode = process.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (exitCode == 0) {
                System.out.println("Python脚本成功运行！输出结果为:\n" + output.toString());
            } else {
                System.err.println("Python脚本运行失败！退出码为:" + exitCode);
            }

            process.destroy();
        }
    }


//    @GetMapping("/test1")
//    public Result test1() throws Exception {
//
//        Qakansa qa = qakansaDao.getByBatch("4087860C");
//        if (qa == null) {
//            log.info("oracle查询失败，未找到数据error ==========================================");
//        } else {
//            log.info("oracle查询success =========================================");
//            String grade = qa.getITM_CD();
//            System.out.println("等级grade -->>>" + grade);
//        }
//        return Result.success();
//    }

    @RequestMapping("LocalCache")
    public String test(Long id) {
        String name = LocalCache.cache.get(String.valueOf(id));
        if (name != null) {
            System.out.println("缓存中存在，查询缓存");
            System.out.println(name);
            return name;
        }
        System.out.println("缓存中不存在，查询数据库");

        name="222";
        LocalCache.cache.put(String.valueOf("1"),"1");
        LocalCache.cache.put(String.valueOf("222"),name);
        System.out.println(name);
        return "111";
    }

    @GetMapping("/test2")
    public Result test2() throws Exception {

        String folderPath = filePathService.getOne(new QueryWrapper<FilePath>().eq("type", "1")).getFilepath();
        File file = new File(folderPath);
        File[] files = file.listFiles();
        String filename = "";
        if (files != null && files.length > 0) {
            for (File f :files) {
                filename = f.getName();
//                log.info("处理文件变化事件=======================================================" + filename);
                // 判断文件后缀.AutoBackup
                if (filename.toLowerCase().contains("backup")) {
                    continue;
                }

                // 处理文件变化事件
                Path changedPath = Paths.get(folderPath + "\\" + filename);
//                log.info("数据处理保存=======================================================");
                if( materialService.saveAutoMaterial(changedPath.toFile())) {
                    // 与机器人交互，启动下料任务
                    // 为6-加热完毕加热炉下降
//                    PLCUtil.writeInt16("VW1002", 6);
//                    log.info("为6-加热完毕加热炉下降");
                }
            }
        }
        return Result.success();
    }
}
